package com.coder.bike.security;

import com.coder.bike.security.handler.CustomerAccessDeniedHandler;
import com.coder.bike.security.handler.CustomerAnonymousEntryPoint;
import com.coder.bike.security.handler.LoginFailHandler;
import com.coder.bike.security.handler.LoginSuccessHandler;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Resource
    private VerifyTokenFilter verifyTokenFilter;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailHandler loginFailHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CustomerAnonymousEntryPoint customerAnonymousEntryPoint;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.addFilterBefore(verifyTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http.formLogin()
                .loginProcessingUrl("/bike/user/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .requestMatchers(
                        "/bike/user/login",                   // 登录
                        "/bike/customer/registerByPhone",     // 注册
                        "/bike/staff/registerByPhone",        // 注册
                        "/bike/auth/resetPasswordByPhone",    // 重置密码
                        "/bike/auth/loginByPhone",            // 手机登录
                        "/sms/**",
                        "/xiangxiang/chat"// 短信接口
                )
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(customerAnonymousEntryPoint)
                .accessDeniedHandler(customerAccessDeniedHandler)
                .and()
                .cors()
                .and()
                .csrf().disable()
                .userDetailsService(customerUserDetailsService);

        return http.build();
    }
}